package com.welink.cmp.gatewayimpl.metadata;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.welink.cmp.convertor.GenericConvertor;
import com.welink.cmp.dao.common.OperationLogService;
import com.welink.cmp.dao.metadata.RouterDaoService;
import com.welink.cmp.dao.metadata.dataobject.RouterDO;
import com.welink.cmp.dao.metadata.dataobject.SwitchDO;
import com.welink.cmp.domain.metadata.Router;
import com.welink.cmp.domain.metadata.Switch;
import com.welink.cmp.domain.metadata.gateway.IRouterGateway;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yanwei li create  2024-06-24 12:07
 */
@Service
@Primary
@Slf4j
public class RouterGatewayImpl implements IRouterGateway {

    @Resource
    private OperationLogService logService;

    @Resource
    private RouterDaoService routerDaoService;

    /**
     * @param router
     * @return
     */
    @Override
    public Router save(Router router) {
        return null;
    }

    /**
     * @param routerList
     * @return
     */
    @Override
    public Boolean saveOrUpdateBatchBySn(List<Router> routerList) {
        //过滤全部 SN
        final List<String> allSnList = routerList.stream().map(Router::getSn).collect(Collectors.toList());
        // 查询已存在
        LambdaQueryWrapper<RouterDO> queryWrapper = Wrappers.lambdaQuery(RouterDO.class);
        queryWrapper.select(RouterDO::getSn).in(RouterDO::getSn,allSnList);
        final List<RouterDO> existSwList = routerDaoService.list(queryWrapper);
        // 已存在的记录 SN-ID
        final Map<String, Long> existFwMap = existSwList.stream().collect(Collectors.toMap(RouterDO::getSn, RouterDO::getId));
        routerList.forEach(switchO -> {
            final Long swId = existFwMap.get(switchO.getSn());
            if ( swId !=null){
                switchO.setId(swId);
            }
        });
        List<RouterDO> allSwitchDoList = GenericConvertor.toDOList(routerList, RouterDO.class);
        // 批量更新
        final boolean rst = routerDaoService.saveOrUpdateBatch(allSwitchDoList);
        log.info("根据 Sn 批量更新或插入交换机[{}]，更新Sn记录{},全部Sn{} ",rst,existSwList,routerList);
        return rst;
    }
}
